import 'package:flutter/material.dart';

class RequestController extends ChangeNotifier {
  List<VoidCallback> _listeners = [];

  /// 加载失败
  bool isLoadFailure = false;

  /// 加载中
  bool isLoading = false;

  /// isCatchFailure: 是否捕捉错误
  /// requestHandler  return 成功 / 失败
  Future<void> start() async {
    isLoadFailure = false;
    isLoading = true;
    notifyListeners();
  }

  Future<void> loadFailure({Duration duration = const Duration(seconds: 1)}) async {
    isLoadFailure = true;
    isLoading = false;
    return Future.delayed(duration, notifyListeners);
  }

  void loadSuccess() {
    isLoadFailure = false;
    isLoading = false;
    notifyListeners();
  }

  @override
  void dispose() {
    _listeners.forEach((element) {
      removeListener(element);
    });
    _listeners.clear();
    super.dispose();
  }

  @override
  void addListener(VoidCallback listener) {
    _listeners.add(listener);
    super.addListener(listener);
  }

  @override
  void notifyListeners() {
    if (_listeners.isEmpty) return;
    super.notifyListeners();
  }
}
